<template>
	<view>
		<view class="uni-header">
			<view class="uni-group">
				<view class="uni-title"></view>
				<view class="uni-sub-title"></view>
			</view>
			<view class="uni-group">
				<input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" />
				<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
				<button class="uni-button" type="default" size="mini" @click="navigateTo('./add')">新增</button>
				<button class="uni-button" type="default" size="mini" :disabled="!selectedIndexs.length"
					@click="delTable">批量删除</button>
				<download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData"
					:type="exportExcel.type" :name="exportExcel.filename">
					<button class="uni-button" type="primary" size="mini">导出 Excel</button>
				</download-excel>
			</view>
		</view>
		<view class="uni-container">
			<unicloud-db ref="udb" :collection="collectionList" :where="where" page-data="replace" :orderby="orderby"
				:getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent"
				v-slot:default="{data,pagination,loading,error,options}" :options="options" loadtime="manual"
				@load="onqueryload">
				<uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe
					type="selection" @selection-change="selectionChange">
					<uni-tr>
						<uni-th align="center" filter-type="search"
						@filter-change="filterChange1($event, 'class_id')">课程名称</uni-th>
						
						<uni-th align="center" filter-type="search"
							@filter-change="filterChange($event, 'homework_title')">作业标题</uni-th>
						<uni-th align="center" filter-type="search"
							@filter-change="filterChange($event, 'homework_detail')">作业详情</uni-th>
						<uni-th align="center">作业图片</uni-th>
						<uni-th align="center">作业视频</uni-th>
						<uni-th align="center" sortable @sort-change="sortChange($event, 'create_homework_time')">创建时间
						</uni-th>
						<uni-th align="center">操作</uni-th>
					</uni-tr>
						<uni-tr  v-for="(item,index) in data" :key="index" v-show="item.is_show">
							<uni-td align="center" v-if="item['is_show']">{{item.class_id[0]["text"]}}</uni-td>
							<uni-td align="center">{{item.homework_title}}</uni-td>
							<uni-td align="center">{{item.homework_detail}}</uni-td>
							<uni-td align="center">
								<template v-for="(file, j) in item.homework_image">
									<image :src="file.url" mode="aspectFit" draggable="true"
										style="width: 10vw;height: 10vh;" @tap="previewImage(file.url)"></image>
								</template>
							</uni-td>
							<uni-td align="center">
								<template v-for="(file, j) in item.homework_video">
									<video :src="file.url" style="width: 10vw;height: 10vh;"></video>
								</template>
							</uni-td>
							<uni-td align="center">
								<!-- 将时间戳转化时分秒 -->
								<uni-dateformat :date="item.create_homework_time"></uni-dateformat></uni-td>
							<uni-td align="center">
								<view class="uni-group">
									<button @click="navigateTo('./edit?id='+item._id, false)" class="uni-button" size="mini"
										type="primary">修改</button>
									<button @click="confirmDelete(item._id)" class="uni-button" size="mini"
										type="warn">删除</button>
								</view>
							</uni-td>
						</uni-tr>
					
				</uni-table>
				<view class="uni-pagination-box">
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
						:total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>
		</view>
	</view>
</template>

<script>
	import {
		enumConverter,
		filterToWhere
	} from '../../js_sdk/validator/assig-homework.js';

	const db = uniCloud.database()
	// 表查询配置
	const dbOrderBy = '' // 排序字段
	const dbSearchFields = [] // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
	// 分页配置
	const pageSize = 20
	const pageCurrent = 1

	const orderByMapping = {
		"ascending": "asc",
		"descending": "desc"
	}

	export default {
		data() {
			return {
				collectionList: [db.collection('assig-homework').field(
						'class_id,homework_title,homework_detail,homework_image,homework_video,create_homework_time,is_show').getTemp(), db
					.collection('class-list').field('_id,class_name as text').getTemp()
				],
				query: '',
				where: '',
				orderby: dbOrderBy,
				orderByFieldName: "",
				selectedIndexs: [],
				options: {
					pageSize,
					pageCurrent,
					filterData: {},
					...enumConverter
				},
				imageStyles: {
					width: 64,
					height: 64
				},
				exportExcel: {
					"filename": "assig-homework.xls",
					"type": "xls",
					"fields": {
						"class_id": "class_id",
						"homework_title": "homework_title",
						"homework_detail": "homework_detail",
						"homework_image": "homework_image",
						"homework_video": "homework_video"
					}
				},
				exportExcelData: [],
				isShow:true
			}
		},
		onLoad() {
			this._filter = {}
		},
		onReady() {
			this.$refs.udb.loadData()
		},
		methods: {
			// 预览图片
			previewImage(url) {
				//字符转化成数组 split直接转化成一个元素,不会将字符串字符分开
				let array_url = url.split()
				//uniapp预览轮播图
				uni.previewImage({
					// current: index, //预览图片的下标
					urls: array_url //预览图片的地址，必须要数组形式，如果不是数组形式就转换成数组形式就可以
				})
			},
			onqueryload(data) {
				this.exportExcelData = data
			},
			getWhere() {
				const query = this.query.trim()
				if (!query) {
					return ''
				}
				const queryRe = new RegExp(query, 'i')
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
			},
			search() {
				const newWhere = this.getWhere()
				this.where = newWhere
				this.$nextTick(() => {
					this.loadData()
				})
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				})
			},
			onPageChanged(e) {
				this.selectedIndexs.length = 0
				this.$refs.table.clearSelection()
				this.$refs.udb.loadData({
					current: e.current
				})
			},
			navigateTo(url, clear) {
				// clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData(clear)
						}
					}
				})
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList
				return this.selectedIndexs.map(i => dataList[i]._id)
			},
			// 批量删除
			delTable() {
				this.$refs.udb.remove(this.selectedItems(), {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			confirmDelete(id) {
				this.$refs.udb.remove(id, {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			sortChange(e, name) {
				this.orderByFieldName = name;
				if (e.order) {
					this.orderby = name + ' ' + orderByMapping[e.order]
				} else {
					this.orderby = ''
				}
				this.$refs.table.clearSelection()
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			filterChange(e, name) {
				this._filter[name] = {
					type: e.filterType,
					value: e.filter
				}
				let newWhere = filterToWhere(this._filter, db.command)
				if (Object.keys(newWhere).length) {
					this.where = newWhere
				} else {
					this.where = ''
				}
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			filterChange1(e,name){
				let filter_name = e['filter'];
				// 获取表格数据
				let data_lists = this.$refs.udb.dataList;
				for (let data_list of data_lists) {
					// 班级名称
					let class_name = data_list["class_id"][0]["text"];
					// 将filter_name和班级名称进行匹配 js 判断字符串中是否包含某个字符串
					let result = class_name.indexOf(filter_name) != -1;
					
					this.isShow = result;
					data_list['is_show'] = result;
					console.log(data_list);
				
				}
				return data_list
				
			}
		}
	}
</script>

<style>
</style>
